package com.yklx.youke.service;

import com.yklx.youke.entity.Booking;
import com.yklx.youke.entity.User;
import com.yklx.youke.entity.YoubiTransaction;
import com.yklx.youke.repository.UserRepository;
import com.yklx.youke.repository.YoubiTransactionRepository;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;

@Service
public class YoubiTransactionService {

    private final YoubiTransactionRepository transactionRepository;
    private final UserRepository userRepository;

    public YoubiTransactionService(YoubiTransactionRepository transactionRepository, UserRepository userRepository) {
        this.transactionRepository = transactionRepository;
        this.userRepository = userRepository;
    }

    public Map<String, Object> getBalance(String userId) {
        // Get user's current Youbi balance
        // In a real implementation, this would sum up all transactions for the user
        // For now, returning a placeholder
        return Map.of("balance", 1000.0, "currency", "YOUBI");
    }

    public YoubiTransaction deposit(String userId, Double amount, String paymentMethod, String externalRef) {
        User user = userRepository.findById(java.util.UUID.fromString(userId))
                .orElseThrow(() -> new IllegalArgumentException("User not found"));

        // In a real implementation, verify payment via payment method first
        YoubiTransaction transaction = new YoubiTransaction();
        transaction.setFromUser(null); // System deposit
        transaction.setToUser(user);
        transaction.setAmount(new BigDecimal(amount.toString()));
        transaction.setTransactionType(YoubiTransaction.TransactionType.DEPOSIT);
        transaction.setDescription("Deposit via " + paymentMethod);
        transaction.setTransactionReference(externalRef);

        return transactionRepository.save(transaction);
    }

    public YoubiTransaction processPayment(String fromUserId, String toUserId, Double amount, String description) {
        User fromUser = userRepository.findById(java.util.UUID.fromString(fromUserId))
                .orElseThrow(() -> new IllegalArgumentException("Sender not found"));
        User toUser = userRepository.findById(java.util.UUID.fromString(toUserId))
                .orElseThrow(() -> new IllegalArgumentException("Recipient not found"));

        // Verify sufficient funds
        double currentBalance = Double.parseDouble(getBalance(fromUserId).get("balance").toString());
        if (currentBalance < amount) {
            throw new IllegalStateException("Insufficient balance");
        }

        YoubiTransaction transaction = new YoubiTransaction(fromUser, toUser, new BigDecimal(amount.toString()), 
                YoubiTransaction.TransactionType.PAYMENT);
        transaction.setDescription(description);

        return transactionRepository.save(transaction);
    }

    public YoubiTransaction processRefund(Booking booking, BigDecimal refundAmount) {
        // Process refund from teacher/assistant to parent
        User parent = booking.getParent();
        User teacher = booking.getSession().getTeacher();

        YoubiTransaction transaction = new YoubiTransaction(teacher, parent, refundAmount, 
                YoubiTransaction.TransactionType.REFUND);
        transaction.setDescription("Refund for cancelled booking " + booking.getBookingId());

        return transactionRepository.save(transaction);
    }

    public YoubiTransaction distributePayment(Booking booking) {
        // Distribute the payment according to platform rules (e.g., 1:9 between assistant and teacher)
        User teacher = booking.getSession().getTeacher();
        User parent = booking.getParent();

        // Calculate amounts based on distribution rules
        BigDecimal totalAmount = booking.getAmount();
        BigDecimal teacherAmount = totalAmount.multiply(new BigDecimal("0.9")); // 90% to teacher
        BigDecimal assistantAmount = totalAmount.multiply(new BigDecimal("0.1")); // 10% to assistant

        // In a real implementation, the assistant would be identified and the payment distributed
        // For now, we'll just record the payment distribution

        YoubiTransaction transaction = new YoubiTransaction(parent, teacher, teacherAmount, 
                YoubiTransaction.TransactionType.DISTRIBUTION);
        transaction.setDescription("Distribution for completed booking " + booking.getBookingId());

        return transactionRepository.save(transaction);
    }
}